use crate::models::catalogs::{self, CreateCatalogParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/catalogs", post(create))
        .route("/catalogs/:id", get(get_by_id))
        .route("/catalogs/:id/delete", post(delete))
        .route("/catalogs/by-slug/:slug", get(get_by_slug))
        .route("/catalogs/by-parent/:parent_id", get(get_by_parent))
        .route("/catalogs/roots", get(get_roots))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateCatalogParams>,
) -> Result<Response> {
    let catalog = catalogs::Model::create(&state.db, &params).await?;
    format::json(catalog)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let catalog = catalogs::Model::find_by_id(&state.db, &id).await?;
    format::json(catalog)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let catalog = catalogs::Model::find_by_id(&state.db, &id).await?;
    catalog.delete(&state.db).await?;
    format::json(())
}

async fn get_by_slug(
    State(state): State<AppContext>,
    axum::extract::Path(slug): axum::extract::Path<String>,
) -> Result<Response> {
    let catalog = catalogs::Model::find_by_slug(&state.db, &slug).await?;
    format::json(catalog)
}

async fn get_by_parent(
    State(state): State<AppContext>,
    axum::extract::Path(parent_id): Path<String>,
) -> Result<Response> {
    let catalogs = catalogs::Model::find_by_parent_id(&state.db, &parent_id).await?;
    format::json(catalogs)
}

async fn get_roots(State(state): State<AppContext>) -> Result<Response> {
    let catalogs = catalogs::Model::find_roots(&state.db).await?;
    format::json(catalogs)
}
